$(function(){
	var localdata=[];
	function getData(){
		if(localStorage.tableList===undefined){
			localdata=[];
		}else{
			localdata=JSON.parse(localStorage.tableList);
		}
		return localdata;
	}
	//console.log(getData());//非要加上条件语句
	
	add();//一开始将原来保存的数据全部都遍历出来,这样就可以实现刷新不会丢失

	function saveData(data){
		localStorage.tableList=JSON.stringify(data);
	}


	function add(){
      $("tr:not(tr:first,tr:last)").remove();//每次增加行前删除前面的行，否则会重复增加
		var data=getData();
		$.each(data,function(i,v){
			$('<tr><td contenteditable="true" name="name">'+v.name+'</td><td contenteditable="true" name="sex">'+v.sex+'</td><td contenteditable="true" name="age">'+v.age+'</td><td contenteditable="true" name="tel">'+v.tel+'</td><td><button class="btn btn-danger btn-sm">删除</button></td></tr>').attr('index',i).insertBefore('tr:last')
		})
	}

    $('.btn-sm').click(function(){
        var data = getData();
        data.push({"name": "", "sex": "", "age": "", "tel": ""});
        saveData(data);
        add();
    })

 	$('table').on('blur','[contenteditable="true"]',function(){
     	var data=getData();
    	var html=$(this).html();
    	var parentIndex=$(this).parent().attr('index');
    	var name=$(this).attr('name');
    	data[parentIndex][name]=html;
    	saveData(data);
	})
    
    $('table').on('click','.btn-danger',function(){
      var data = getData();
      var index = $(this).parent().parent().attr("index");
      data.splice(index,1);
      add();
      saveData(data);
    })
    
})